package longestCommonPrefix;

/*  编写一个函数来查找字符串数组中的最长公共前缀。
    如果不存在公共前缀，返回空字符串 ""。

    输入：strs = ["flower","flow","flight", "fl"]
    输出："fl"


    输入：strs = ["dog","racecar","car"]
    输出：""
    解释：输入不存在公共前缀。
*/

class Solution {
    public static String longestCommonPrefix(String[] strs) {
        String pre = "";

        // 最短字符串
        String shortStr = strs[0];
        // 遍历收个数据字符
        for (int j = 0; j < shortStr.length(); j++) {
            for (int i = 1; i < strs.length; i++) {
                if (strs[i].length()-1 < j || shortStr.charAt(j) != strs[i].charAt(j)) {
                    return pre;
                }
            }
            // 字符串相加性能消耗大
            pre += shortStr.charAt(j);
        }
        return pre;
    }

    public static void main(String[] args) {
        String[] strs = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix(strs));
    }
}